/**
 * 
 */
package com.jcore1.chapter5;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 *
 */
public class ObjectAnalyzer {

	private List<Object> visited = new ArrayList<>();

	/** 通用toString 函数
	 * @param obj 将要打印的对象
	 * @return 对象字符串信息
	 * @throws IllegalArgumentException 参数异常，非法参数
	 * @throws IllegalAccessException 获取权限异常
	 */
	@SuppressWarnings("rawtypes")
	public String toString(Object obj) throws IllegalArgumentException, IllegalAccessException {
		if (null == obj) {
			return "null";
		}
		if (visited.contains(obj)) {
			return "...";
		}
		visited.add(obj);
		Class cl = obj.getClass();
		if (cl == String.class) {
			return (String) obj;
		}
		if (cl.isArray()) {
			String r = cl.getComponentType() + "[]{";
			for (int i = 0; i < Array.getLength(obj); i++) {
				// 增加逗号
				if (i > 0) {
					r += ",";
				}
				Object val = Array.get(obj, i);
				// 判断是否是基本类型
				if (cl.getComponentType().isPrimitive()) {
					r += val;
				}
				r += toString(val);
			}

			r += "}";
			return r;
		}

		String r = cl.getName();
		do {
			r += "[";
			Field[] fields = cl.getDeclaredFields();
			AccessibleObject.setAccessible(fields, true);
			for (Field field : fields) {
				if (!Modifier.isStatic(field.getModifiers())) {
					if (!r.endsWith("[")) {
						r += ",";
					}
					r += field.getName() + "=";
					Class t = field.getType();
					Object val = field.get(obj);
					if (t.isPrimitive()) {
						r += val;
					} else {
						r += toString(val);
					}
				}
			}

			r += "]";
			cl = cl.getSuperclass();
		} while (null != cl);
		return r;
	}

}
